package com.ruoyi.training.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.utils.SmsVerificationUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.training.domain.NoticeReceive;
import com.ruoyi.training.domain.Students;
import com.ruoyi.training.dto.StudentNoticeDto;
import com.ruoyi.training.service.IClassStudentService;
import com.ruoyi.training.service.INoticeReceiveService;
import com.ruoyi.training.service.IStudentsService;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import com.ruoyi.training.vo.StudentNoticeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.training.mapper.StudentNoticeMapper;
import com.ruoyi.training.domain.StudentNotice;
import com.ruoyi.training.service.IStudentNoticeService;

/**
 * 学员通知Service业务层处理
 *
 * @author lqx
 * @date 2025-10-24
 */
@Service
public class StudentNoticeServiceImpl implements IStudentNoticeService
{
    private static final SnowflakeIdUtils snowflake = new SnowflakeIdUtils(5, 8);

    @Autowired
    private StudentNoticeMapper studentNoticeMapper;

    @Autowired
    private IClassStudentService classStudentService;

    @Autowired
    private INoticeReceiveService noticeReceiveService;

    @Autowired
    private IStudentsService studentsService;

    /**
     * 查询学员通知
     *
     * @param studentNoticeId 学员通知主键
     * @return 学员通知
     */
    @Override
    public StudentNotice selectStudentNoticeByStudentNoticeId(String studentNoticeId)
    {
        return studentNoticeMapper.selectStudentNoticeByStudentNoticeId(studentNoticeId);
    }

    /**
     * 查询学员通知列表
     *
     * @param studentNotice 学员通知
     * @return 学员通知
     */
    @Override
    public List<StudentNotice> selectStudentNoticeList(StudentNotice studentNotice)
    {
        return studentNoticeMapper.selectStudentNoticeList(studentNotice);
    }

    /**
     * 新增学员通知
     *
     * @param studentNotice 学员通知
     * @return 结果
     */
    @Override
    public int insertStudentNotice(StudentNotice studentNotice)
    {
        return studentNoticeMapper.insertStudentNotice(studentNotice);
    }

    /**
     * 修改学员通知
     *
     * @param studentNotice 学员通知
     * @return 结果
     */
    @Override
    public int updateStudentNotice(StudentNotice studentNotice)
    {
        return studentNoticeMapper.updateStudentNotice(studentNotice);
    }

    /**
     * 批量删除学员通知
     *
     * @param studentNoticeIds 需要删除的学员通知主键
     * @return 结果
     */
    @Override
    public int deleteStudentNoticeByStudentNoticeIds(String[] studentNoticeIds)
    {
        return studentNoticeMapper.deleteStudentNoticeByStudentNoticeIds(studentNoticeIds);
    }

    /**
     * 删除学员通知信息
     *
     * @param studentNoticeId 学员通知主键
     * @return 结果
     */
    @Override
    public int deleteStudentNoticeByStudentNoticeId(String studentNoticeId)
    {
        return studentNoticeMapper.deleteStudentNoticeByStudentNoticeId(studentNoticeId);
    }

    /**
     * 学员通知处理
     * lqx
     */
    @Override
    public int studentNoticeProcess(StudentNoticeDto studentNoticeDto) throws Exception{
        // 1. 生成通知ID
        String studentNoticeId = String.valueOf(snowflake.nextId());

        // 2. 处理学员ID数组（根据发送类型）
        List<String> studentIds = getStudentIds(studentNoticeDto);
        if (studentIds.isEmpty()) {
            return 90;//返回90表示当前班级下学员ids为空或者指定学员ids为空
        }

        // 3. 保存通知主记录
        StudentNotice studentNotice = new StudentNotice();
        //复制信息
        BeanUtils.copyProperties(studentNoticeDto,studentNotice);
        //设置主键id
        studentNotice.setStudentNoticeId(studentNoticeId);
        //设置创建者
        studentNotice.setSendBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
//        studentNotice.setSendBy("张三");
        //设置创建时间
        studentNotice.setCreateTime(new Date());
        studentNoticeMapper.insertStudentNotice(studentNotice);

        // 4. 查询学员信息（姓名、手机号）
        List<Students> students = studentsService.selectStudentsByIds(studentIds);
        System.out.println("students = " + students.toString());
        if (students.isEmpty()) {
            return 91;//返回91表示未查询到学员信息
        }

        // 5. 处理短信发送（若需要）
        int smsSendResult = handleSmsSend(studentNoticeDto, students);

        // 6. 构建并保存接收记录到通知接收表
        List<NoticeReceive> noticeReceiveList = buildReceivers(students, studentNotice, smsSendResult);
        noticeReceiveService.batchInsertnoticeReceive(noticeReceiveList);
        return 100;
    }

    /**
     * 通过班级id查询通知详情
     * lqx
     */
    @Override
    public List<StudentNoticeVo> selectListByClassId(String trainingClassId) {
        List<StudentNotice> studentNoticeList = studentNoticeMapper.selectListByClassId(trainingClassId);
        System.out.println("studentNoticeList =" + studentNoticeList);
        List<StudentNoticeVo> studentNoticeVoList = new ArrayList<>();
        for (StudentNotice studentNotice : studentNoticeList) {
            StudentNoticeVo studentNoticeVo = new StudentNoticeVo();
            //复制值
            BeanUtils.copyProperties(studentNotice,studentNoticeVo);
            //通知渠道
            String noticeChannel = "";
            if (studentNoticeVo.getIsSms() != null && !"".equals(studentNoticeVo.getIsSms())){
                noticeChannel = noticeChannel +  "短信";
            }
            if (studentNoticeVo.getIsPortal() != null && !"".equals(studentNoticeVo.getIsPortal())){
                if (noticeChannel != null && !"".equals(noticeChannel)){
                    noticeChannel = noticeChannel +  ";门户推送";
                }else {
                    noticeChannel = noticeChannel +  "门户推送";
                }
            }
            //通知人员
            if ("1".equals(studentNoticeVo.getSendType())){
                studentNoticeVo.setNoticeStudents("全体学员");
            }else {
                List<Students> studentsList = studentsService.selectStudentsByStudentNoticeId(studentNoticeVo.getStudentNoticeId());
                String StudentName = "";
                for (Students students : studentsList) {
                    if (StudentName != null && !"".equals(StudentName)){
                        StudentName = StudentName + ";" + students.getStudentName();
                    }else {
                        StudentName = students.getStudentName();
                    }
                }
                studentNoticeVo.setNoticeStudents(StudentName);
            }
            studentNoticeVo.setNoticeChannel(noticeChannel);
            studentNoticeVoList.add(studentNoticeVo);
        }
        return studentNoticeVoList;
    }

    // 根据发送类型获取学员ID数组
    private List<String> getStudentIds(StudentNoticeDto studentNoticeDto) {
        if ("1".equals(studentNoticeDto.getSendType())) {
            // 全体学员：通过班级ID查询
            return classStudentService.selectStudentIdsByClassId(studentNoticeDto.getTrainingClassId());
        } else {
            // 指定学员：直接使用传入的ID数组
            return studentNoticeDto.getStudentIds() != null ? studentNoticeDto.getStudentIds() : new ArrayList<>();
        }
    }
    // 处理短信发送
    private int handleSmsSend(StudentNoticeDto studentNoticeDto, List<Students> students) throws Exception {
        //判断是否走短信渠道
        if ("1".equals(studentNoticeDto.getIsSms())) {
            // 1. 拼接手机号（英文逗号分隔）
            String mobiles = students.stream()
                    .map(Students::getPhonenumber)
                    .collect(Collectors.joining(","));
            // 2. 调用短信工具类
            int smsResult = SmsVerificationUtils.sendSMS(
                    mobiles,
                    studentNoticeDto.getNoticeContent(),
                    formatSendTime(studentNoticeDto.getSendTime())
            );
            // 3. 判断短信工具类返回消息
            if (smsResult > 0){//大于0表示发送成功
                return 0;
            }else {//小于0表示发送失败
                return 1;
            }
        }else {
            return 2;
        }
    }
    // 格式化发送时间为14位字符串（为空则立即发送）
    private String formatSendTime(Date inputTime) {
        if (inputTime == null) {
            return ""; // 空表示立即发送
        }
        // 格式化Date为14位字符串（yyyyMMddHHmmss）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(inputTime);
    }
    // 构建接收记录
    private List<NoticeReceive> buildReceivers(List<Students> students,StudentNotice studentNotice, int smsStatusMap) {
        List<NoticeReceive> noticeReceiveList = new ArrayList<>();
        for (Students student : students) {//循环学员来添加数据
            NoticeReceive noticeReceive = new NoticeReceive();
            //设置组件id
            noticeReceive.setNoticeReceiveId(String.valueOf(snowflake.nextId()));
            //设置学员通知表id
            noticeReceive.setStudentNoticeId(studentNotice.getStudentNoticeId());
            //设置学员id
            noticeReceive.setStudentId(student.getStudentId());
            //设置班级id
            noticeReceive.setTrainingClassId(studentNotice.getTrainingClassId());
            //设置短信状态
            noticeReceive.setSmsStatus(String.valueOf(smsStatusMap));
            // 设置门户状态
            {
                if ("1".equals(studentNotice.getIsPortal())){
                    noticeReceive.setPortalStatus("0");
                }else {
                    noticeReceive.setPortalStatus("1");
                }
            }
            //设置创建时间
            noticeReceive.setCreateTime(new Date());
            noticeReceiveList.add(noticeReceive);
        }
        return noticeReceiveList;
    }
}
